package liecai_class.day09;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Atomic原子性操作 - AtomicInteger
 */
public class Demo02 {
    private static AtomicInteger x = new AtomicInteger(0);
    public static void main(String[] args) throws InterruptedException {
        CountDownLatch cdl = new CountDownLatch(2);
        new Thread(new Runnable() {
            @Override
            public void run() {
                for(int i = 0;i<100000;i++){
                    boolean isOK = false;
                    while(!isOK) {
                        int oldValue = x.get();
                        int newValue = oldValue + 1;
                        isOK = x.compareAndSet(oldValue, newValue);
                    }
                }
                cdl.countDown();
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                for(int i = 0;i<100000;i++){
                    while(!x.compareAndSet(x.get(), x.get()+1)){
                    }
                }
                cdl.countDown();
            }
        }).start();

        cdl.await();
        System.out.println(x);
    }
}